import React, { useState, useEffect } from 'react';

const MatrixInput = ({ title, matrix, onMatrixChange, dimensions }) => {
    const { rows, cols } = dimensions;
    const [parsedMatrix, setParsedMatrix] = useState(matrix);

    useEffect(() => {
        const newMatrix = Array(rows).fill().map(() => Array(cols).fill(0));

        // 填充已有数据
        for (let i = 0; i < Math.min(rows, matrix.length); i++) {
            for (let j = 0; j < Math.min(cols, matrix[i]?.length || 0); j++) {
                newMatrix[i][j] = matrix[i][j];
            }
        }

        setParsedMatrix(newMatrix);
    }, [matrix, rows, cols]);

    const handleCellChange = (row, col, value) => {
        const newMatrix = [...parsedMatrix];
        newMatrix[row][col] = isNaN(parseInt(value)) ? 0 : parseInt(value);
        onMatrixChange(newMatrix);
    };

    const handlePaste = (e, row) => {
        e.preventDefault();
        const pastedText = e.clipboardData.getData('text/plain').trim();
        const lines = pastedText.split('\n').filter(line => line.trim() !== '');

        const newMatrix = [...parsedMatrix];

        for (let i = 0; i < Math.min(rows - row, lines.length); i++) {
            const values = lines[i].split(/[\s\t,;|]+/).filter(val => val !== '');

            for (let j = 0; j < Math.min(cols, values.length); j++) {
                newMatrix[row + i][j] = isNaN(parseInt(values[j])) ? 0 : parseInt(values[j]);
            }
        }

        onMatrixChange(newMatrix);
    };

    const renderHeader = () => (
        <tr>
            <th className="row-header">进程</th>
            {[...Array(cols)].map((_, j) => (
                <th key={`col-header-${j}`}>
                    <span>资源</span>
                    <span className="index">{j + 1}</span>
                </th>
            ))}
        </tr>
    );

    const renderRows = () => parsedMatrix.map((row, i) => (
        <tr key={`row-${i}`}>
            <td className="row-header">
                <span>进程</span>
                <span className="index">{i + 1}</span>
            </td>
            {row.map((value, j) => (
                <td key={`cell-${i}-${j}`}>
                    <input
                        type="number"
                        min="0"
                        value={value}
                        onChange={(e) => handleCellChange(i, j, e.target.value)}
                        onPaste={(e) => handlePaste(e, i)}
                    />
                </td>
            ))}
        </tr>
    ));

    return (
        <div className="matrix-input">
            <h3>{title}</h3>
            <div className="matrix-container">
                <table>
                    <thead>{renderHeader()}</thead>
                    <tbody>{renderRows()}</tbody>
                </table>
            </div>
            <div className="matrix-hint">
                <p>输入提示：</p>
                <ul>
                    <li>可以复制Excel或文本中的表格直接粘贴（支持逗号、分号、制表符分隔）</li>
                    <li>负数会自动转换为0</li>
                    <li>通过键盘方向键或Tab键快速导航</li>
                </ul>
            </div>
        </div>
    );
};

export default MatrixInput;